import i18n from './index';

export const loadLanguageAsync = async (lang: string) => {
    const { locale, availableLocales, setLocaleMessage } = i18n.global;
    if (availableLocales.includes(lang)) {
        locale.value = lang;
        localStorage.setItem('lang', lang); // 更新存储的语言信息
        return Promise.resolve();
    }
    try {
        const messages = await import(`./locales/${lang}.json`);
        setLocaleMessage(lang, messages.default);
        locale.value = lang;
        localStorage.setItem('lang', lang); // 更新存储的语言信息
    } catch (error) {
        console.error(`Failed to load language file for ${lang}:`, error);
    }
};

export const initLoadLanguage = async (lang: string) => {
    const { locale, setLocaleMessage } = i18n.global;

    try {
        const messages = await import(`./locales/${lang}.json`);
        setLocaleMessage(lang, messages.default);
        locale.value = lang;
        localStorage.setItem('lang', lang); // 更新存储的语言信息
    } catch (error) {
        console.error(`Failed to load language file for ${lang}:`, error);
    }
};
